package org.ams.account.controller;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;

import org.ams.account.entity.Account;
import org.ams.account.service.AccountService;
import org.ams.common.annotation.Log;
import org.ams.common.entity.Pager;
import org.ams.common.exception.SystemException;
import org.ams.common.util.Common;
import org.ams.role.entity.Role;
import org.ams.role.entity.RoleAccount;
import org.ams.role.service.RoleService;
import org.apache.shiro.crypto.SecureRandomNumberGenerator;
import org.apache.shiro.crypto.hash.Md5Hash;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;

import com.alibaba.fastjson.JSON;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;

@Controller
@Scope("prototype")
@RequestMapping(value = "/account")
public class AccountController {
	
	@Resource
	private AccountService accountService;
	
	@Resource
	private RoleService roleService;

	@RequestMapping(value = "/main", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	public String main(HttpServletRequest request) {
		try{
			request.removeAttribute("error");
			return Common.VIEW_PATH + "/account/list";
		} catch(Exception e) {
			throw new SystemException(e);
		}
	}
	
	@RequestMapping(value = "/list", method = RequestMethod.POST)
	@ResponseBody
	@Log(module="系统基础管理",methods="用户管理-查询")//凡需要处理业务逻辑的.都需要记录操作日志
	public Map<String, Object> list(HttpServletRequest request,@RequestParam ("dtGridPager") String dtGridPager) {
		Map<String, Object> params = null;
		// 映射Pager对象
		Pager pager = JSON.parseObject(dtGridPager, Pager.class);
		// 判断是否包含自定义参数
		params = pager.getParameters();
		// 设置分页，page里面包含了分页信息
		Page<Object> page = PageHelper.startPage(pager.getNowPage(),pager.getPageSize(), true);
		List<Account> accountList = accountService.queryAccountListByPage(params);
		params.clear();
		params.put("isSuccess", Boolean.TRUE);
		params.put("nowPage", pager.getNowPage());
		params.put("pageSize", pager.getPageSize());
		params.put("pageCount", page.getPages());
		params.put("recordCount", page.getTotal());
		params.put("startRecord", page.getStartRow());
		//列表展示数据
		params.put("exhibitDatas", accountList);
		return params;
	}
	
	@RequestMapping(value = "/delete", method = RequestMethod.POST)
	@ResponseBody
	@Log(module="系统基础管理",methods="用户管理-删除")//凡需要处理业务逻辑的.都需要记录操作日志
	public Boolean delete(HttpServletRequest request,@RequestParam("ids") String accountIds) {
		Map<String, Object> params = new HashMap<String, Object>();
		List<Integer> idList = Common.createIdList(accountIds, ",");
		params.put("idList", idList);
		Integer returnRows = accountService.deleteAccountsByIds(params);
		if(0 < returnRows){
			return true;
		} else {
			return false;
		}
	}
	
	@RequestMapping(value = "/add", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	@Log(module="系统基础管理",methods="用户管理-新增")//凡需要处理业务逻辑的.都需要记录操作日志
	public String add(HttpServletRequest request, Model model) {
		try{
			request.removeAttribute("error");
			List<Role> roleList = roleService.queryRoleListByMap(new HashMap<String, Object>());
			model.addAttribute("roleList", roleList);
			model.addAttribute("operation", "add");
			return Common.VIEW_PATH + "/account/info";
		} catch(Exception e) {
			throw new SystemException(e);
		}
	}
	
	@RequestMapping(value = "/{accountId}/edit", method = RequestMethod.GET, produces = "text/html; charset=utf-8")
	@Log(module="系统基础管理",methods="用户管理-编辑")//凡需要处理业务逻辑的.都需要记录操作日志
	public String edit(HttpServletRequest request,@PathVariable("accountId") Integer accountId, Model model) {
		try{
			request.removeAttribute("error");
			List<Role> roleList = roleService.queryRoleListByMap(new HashMap<String, Object>());
			model.addAttribute("roleList", roleList);
			Account account = accountService.queryAccountByAccountId(accountId);
			List<RoleAccount> roleAccountList = roleService.queryRoleAccountListByAccountId(accountId);
			for (RoleAccount roleAccount : roleAccountList) {
				for (Role role : roleList) {
					if(role.getRoleId().toString().equals(roleAccount.getRoleId().toString())){
						role.setChecked(true);
					}
				}
			}
			model.addAttribute("operation", "edit");
			model.addAttribute("account", account);
			return Common.VIEW_PATH + "/account/info";
		} catch(Exception e) {
			throw new SystemException(e);
		}
	}
	
	@RequestMapping(value = "/save", method = RequestMethod.POST)
	@ResponseBody
	@Log(module="系统基础管理",methods="用户管理-保存")//凡需要处理业务逻辑的.都需要记录操作日志
	public Boolean save(HttpServletRequest request, Account account) {
		if(null != account.getAccountId() && 0 < account.getAccountId()){
			account.setUpdateTime(new Date());
			Integer returnRows = accountService.updateAccount(account);
			if(0 < returnRows) {
				return true;
			} else {
				return false;
			}
		} else {
			account.setCreator(Common.getloginAccountId());
			account.setCreateTime(new Date());
			account.setUpdateTime(new Date());
			SecureRandomNumberGenerator secureRandomNumberGenerator=new SecureRandomNumberGenerator(); 
	        String salt= secureRandomNumberGenerator.nextBytes().toHex(); 
	        //组合username,两次迭代，对密码进行加密 
	        String password_cryto = new Md5Hash(account.getPassword(), account.getAccountName() + salt, 2).toBase64();
	        account.setPassword(password_cryto);
	        account.setCredentialsSalt(salt);
	        Integer returnRows = accountService.saveAccount(account);
			if(0 < returnRows){
				return true;
			} else {
				return false;
			}
		}
	}
	
	@RequestMapping(value = "/reset", method = RequestMethod.POST)
	@ResponseBody
	@Log(module="系统基础管理",methods="用户管理-重置密码")//凡需要处理业务逻辑的.都需要记录操作日志
	public Boolean resetPwd(HttpServletRequest request,@RequestParam("ids") String accountIds) {
		Integer returnRows = 0;
		List<Integer> idList = Common.createIdList(accountIds, ",");
		for (Integer accountId : idList) {
			Account account = accountService.queryAccountByAccountId(accountId);
			String password_cryto = new Md5Hash("123456", account.getAccountName() + account.getCredentialsSalt(), 2).toBase64();
			account.setPassword(password_cryto);
			returnRows = returnRows + accountService.updateAccount(account);
		}
		if(returnRows == idList.size()){
			return true;
		} else {
			return false;
		}
	}
}
